const si = require('systeminformation');
const os = require('os');
const { exec } = require('child_process');
const util = require('util');

const execPromise = util.promisify(exec);

/**
 * 获取系统基本信息
 */
exports.getSystemInfo = async () => {
  try {
    const [cpu, mem, disk, osInfo, network, processes] = await Promise.all([
      si.currentLoad(),
      si.mem(),
      si.fsSize(),
      si.osInfo(),
      si.networkStats(),
      si.processes()
    ]);

    return {
      cpu: {
        load: cpu.currentLoad.toFixed(2),
        cores: os.cpus().length,
        model: os.cpus()[0].model,
        speed: os.cpus()[0].speed
      },
      memory: {
        total: (mem.total / 1024 / 1024 / 1024).toFixed(2), // GB
        used: (mem.used / 1024 / 1024 / 1024).toFixed(2), // GB
        usedPercent: (mem.used / mem.total * 100).toFixed(2)
      },
      disk: disk.map(item => ({
        fs: item.fs,
        type: item.type,
        size: (item.size / 1024 / 1024 / 1024).toFixed(2), // GB
        used: (item.used / 1024 / 1024 / 1024).toFixed(2), // GB
        usedPercent: item.use.toFixed(2),
        mount: item.mount
      })),
      os: {
        platform: osInfo.platform,
        distro: osInfo.distro,
        release: osInfo.release,
        kernel: osInfo.kernel,
        arch: osInfo.arch,
        hostname: os.hostname(),
        uptime: os.uptime()
      },
      network: network.map(item => ({
        interface: item.iface,
        rx_bytes: (item.rx_bytes / 1024 / 1024).toFixed(2), // MB
        tx_bytes: (item.tx_bytes / 1024 / 1024).toFixed(2), // MB
        rx_sec: (item.rx_sec / 1024).toFixed(2), // KB/s
        tx_sec: (item.tx_sec / 1024).toFixed(2) // KB/s
      })),
      processes: {
        all: processes.all,
        running: processes.running,
        blocked: processes.blocked,
        sleeping: processes.sleeping
      },
      timestamp: Date.now()
    };
  } catch (error) {
    throw new Error(`获取系统信息失败: ${error.message}`);
  }
};

/**
 * 获取系统当前进程列表
 */
exports.getProcessList = async () => {
  try {
    const { stdout } = await execPromise('ps -aux --sort=-%cpu | head -11');
    const lines = stdout.trim().split('\n');
    const headers = lines[0].split(/\s+/).filter(Boolean);
    
    const processes = lines.slice(1).map(line => {
      const parts = line.trim().split(/\s+/);
      const result = {};
      
      // 确保有足够的列
      headers.forEach((header, index) => {
        if (index < parts.length) {
          result[header.toLowerCase()] = parts[index];
        }
      });
      
      // 合并命令部分
      if (headers.length < parts.length) {
        result.command = parts.slice(headers.length - 1).join(' ');
      }
      
      return result;
    });
    
    return processes;
  } catch (error) {
    throw new Error(`获取进程列表失败: ${error.message}`);
  }
};

/**
 * 获取系统服务状态
 */
exports.getServicesStatus = async () => {
  try {
    const services = ['nginx', 'mysql', 'mongodb', 'redis', 'docker', 'ssh'];
    const results = {};
    
    for (const service of services) {
      try {
        await execPromise(`systemctl is-active ${service}`);
        results[service] = 'active';
      } catch (err) {
        if (err.stderr.includes('not-found')) {
          results[service] = 'not-installed';
        } else {
          results[service] = 'inactive';
        }
      }
    }
    
    return results;
  } catch (error) {
    throw new Error(`获取服务状态失败: ${error.message}`);
  }
};

/**
 * 获取网络连接状态
 */
exports.getNetworkConnections = async () => {
  try {
    const { stdout } = await execPromise('netstat -tuln | grep LISTEN');
    const lines = stdout.trim().split('\n');
    
    const connections = lines.map(line => {
      const parts = line.trim().split(/\s+/);
      const localAddress = parts[3];
      const [ip, port] = localAddress.split(':');
      
      return {
        protocol: parts[0],
        localAddress,
        ip,
        port,
        state: parts[5] || 'LISTEN'
      };
    });
    
    return connections;
  } catch (error) {
    throw new Error(`获取网络连接失败: ${error.message}`);
  }
}; 